<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}
        /resources/admin/easyui/ui/themes/default/easyui.css"/>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}
        /resources/admin/easyui/css/wu.css"/>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}
        /resources/admin/easyui/css/icon.css"/>
    <script type="text/javascript" src="${pageContext.request.contextPath}
        /resources/admin/easyui/js/jquery.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}
        /resources/admin/easyui/ui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}
        /resources/admin/easyui/ui/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>
<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'west',border:true,split:true," title="菜单管理" style="width:150px; padding:5px;">
        <ul id="wu-category-tree" class="easyui-tree"></ul>
    </div>
    <div data-options="region:'center',border:false">
        <!-- Begin of toolbar -->
        <div id="wu-toolbar">
            <div class="wu-toolbar-button">
                <a href="#" class="easyui-linkbutton" iconCls="icon-add" onclick="openAdd()" plain="true">添加</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-edit" onclick="openEdit()" plain="true">修改</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-remove" onclick="remove()" plain="true">删除</a>
            </div>
            <div class="wu-toolbar-search">
                <label>关键词：</label><input class="wu-text" style="width:100px" id="search-value">
                <a id="search-btn" href="#" class="easyui-linkbutton" iconCls="icon-search">开始检索</a>
            </div>
        </div>
        <!-- End of toolbar -->
        <table id="wu-datagrid" class="easyui-treegrid" toolbar="#wu-toolbar"></table>
    </div>
</div>

<style>
    .active {
        background: green;
    }
</style>
<!-- Begin of easyui-dialog -->

<%-- 用户添加部分start --%>
<div id="add-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="add-form" method="post">
        <table>
            <tr>
                <td width="60" align="right">用户名:</td>
                <td><input type="text" name="name" id="add_name" value="" class="wu-text"/></td>
            </tr>
            <tr>
                <td align="right">用户备注:</td>
                <td>
                    <input name="remark" id="add_remark" class="easyui-textbox" data-options="multiline:true"
                           value="This TextBox will allow the user to enter multiple lines of text."
                           style="width:300px;height:100px">
                </td>
            </tr>

            <%--<tr>--%>
            <%--<td align="right">菜单url:</td>--%>
            <%--<td><input type="text" name="url" id="url" value="" class="wu-text" /></td>--%>
            <%--</tr>--%>
            <%--<tr>--%>
            <%--<td valign="top" align="right">菜单图标:</td>--%>
            <%--<td>--%>
            <%--<input name="icon" id="add-icon" style="width:260px" data-options="required:true,missingMessage:'请填写菜单图标'"></input>--%>
            <%--<a href="#" class="easyui-linkbutton" iconCls="icon-add" onclick="addIcon()" plain="true">添加图标</a>--%>
            <%--</td>--%>
            <%--</tr>--%>
        </table>
    </form>
</div>
<%-- 用户添加部分end --%>


<%-- 用户编辑start --%>
<div id="edit-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="edit-form" method="post">
        <input type="hidden" id="edit_id" name="id"/>
        <table>
            <tr>
                <td width="60" align="right">用户名称:</td>
                <td><input type="text" id="edit_name" name="name" value="" class="wu-text"/></td>
            </tr>
            <tr>
                <td align="right">备注:</td>
                <td>
                    <input id="edit_remark" name="remark" class="easyui-textbox" data-options="multiline:true"
                           value="This TextBox will allow the user to enter multiple lines of text."
                           style="width:300px;height:100px">

                    <%--<select id="remark" name="edit_remark" class="easyui-combobox" panelHeight="auto" style="width:100px">--%>
                    <%--<c:forEach items="${topList}" var="list">--%>
                    <%--<option value="1">${list.menu_name}</option>--%>
                    <%--</c:forEach>--%>
                    <%--</select>--%>
                </td>
            </tr>
            <%--<tr>--%>
            <%--<td align="right">菜单url:</td>--%>
            <%--<td><input id="edit_url" type="text" name="url" value="" class="wu-text" /></td>--%>
            <%--</tr>--%>
            <%--<tr>--%>
            <%--<td valign="top" align="right">菜单图标:</td>--%>
            <%--<td>--%>
            <%--<input id="edit_icon" name="icon" style="width:260px" data-options="required:true,missingMessage:'请填写菜单图标'"></input>--%>
            <%--<a href="#" class="easyui-linkbutton" iconCls="icon-edit" onclick="addIcon()" plain="true">添加图标</a>--%>
            <%--</td>--%>
            <%--</tr>--%>
        </table>
    </form>
</div>
<%-- 用户编辑end --%>

<%-- 编辑角色权限start --%>
<div id="auth-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'" style="width:400px; height:500px; padding:10px;">
    <ul id="auth-tree" class="easyui-tree" checkbox="true">

    </ul>
</div>
<%-- 编辑角色权限end --%>

<div id="icon-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="height:500px;width:580px;
        padding:10px;">

    <form id="icon-form" method="post">
        <table id="icon-table">
        </table>
    </form>
</div>
<!-- End of easyui-dialog -->
<script type="text/javascript">
    var existAuthority = null;

    // 判断是否有父类
    function haveParent(rows, parentId) {
        for(var i=0; i<rows.length; i++) {
            if (rows[i].id == parentId) {
                if (rows[i].parentId != 0) {
                    return true;
                }
            }
        }
        return false;
    }

    // 判断是否被添加
    function isAdded(row, rows) {
        for(var k=0; k<existAuthority.length;k++) {
            if (existAuthority[k].menuId == row.id && haveParent(rows, row.parentId)) return true;
        }
        return false;
    }


    function convert(rows){


        // 判断是否有父类
        function exists(rows, parentId){
            for(var i=0; i<rows.length; i++){
                if (rows[i].id == parentId) return true;
            }
            return false;
        }

        var nodes = [];
        // get the top level nodes
        for(var i=0; i<rows.length; i++){
            var row = rows[i];
            if (!exists(rows, row.parentId)){
                nodes.push({
                    id:row.id,
                    text:row.menu_name
                });
            }
        }

        var toDo = [];
        for(var i=0; i<nodes.length; i++){
            toDo.push(nodes[i]);
        }
        while(toDo.length){
            var node = toDo.shift();	// the parent node
            // get the children nodes
            for(var i=0; i<rows.length; i++){
                var row = rows[i];
                if (row.parentId == node.id){
                    var child = {id:row.id,text:row.menu_name};
                    if (isAdded(row, rows)) {
                        child.checked = true;
                    }
                    if (node.children){
                        node.children.push(child);
                    } else {
                        node.children = [child];
                    }
                    toDo.push(child);
                }
            }
        }
        return nodes;
    }

    /*
    * 编辑角色权限
    * */
    function handleAuthEdit(roleId) {


        $('#auth-dialog').dialog({
            closed: false,
            modal: true,
            title: "编辑角色权限",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: authEdit
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#auth-dialog').dialog('close');
                }
            }],
            onBeforeOpen: function() {


                $.ajax({
                    url: '${pageContext.request.contextPath}/role/get_authority_list',
                    type: 'post',
                    data: {roleId: roleId},
                    dataType: 'json',
                    success: function(data) {
                        existAuthority = data;
                    }
                })

                $('#auth-tree').tree({
                    url: "${pageContext.request.contextPath}/role/get_all_menu_list",
                    loadFilter: function(rows){
                        return convert(rows);
                    }
                })
            }
        });
    }

    function authEdit() {
        var item = $('#wu-datagrid').treegrid('getSelected');
        console.log(item)
        if (item.id == null) {
            $.messager.alert('信息提示', '请选择要删除的角色', 'warning');
            return;
        }

        var ids = '';
        var childrenNodes = $('#auth-tree').tree('getChecked');
        for(var i=0; i<childrenNodes.length; i++) {
            ids += childrenNodes[i].id + ',';
        }

        var parentNodes = $('#auth-tree').tree('getChecked', 'indeterminate');
        for(var i=0; i<parentNodes.length; i++) {
            ids += parentNodes[i].id + ',';
        }

        $.ajax({
            url: '${pageContext.request.contextPath}/role/add_authority',
            type: 'post',
            data: {ids: ids, roleId: item.id},
            dataType: 'json',
            success: function(data) {
                if (data.type == 'success') {
                    $.messager.alert('信息提示', data.msg, 'info');
                    $('#auth-dialog').dialog('close');
                } else {
                    $.messager.alert('信息提示', data.msg, 'info');
                }
            }
        })
    }

    /*
    * 搜索
    * */
    $('#search-btn').click(function () {
        $('#wu-datagrid').treegrid('reload', {
            'name': $('#search-value').val()
        })
    })


    function select_icon(e) {
        $('.icon-td').removeClass('active');
        $(e).parent('td').addClass('active');
    }

    function addIcon() {
        if ($('#icon-table').children().length <= 0) {
            $.ajax({
                url: '${pageContext.request.contextPath}/menu/select_icon',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    if (data.type == 'success') {
                        var icon = data.icons;
                        var table = '';

                        for (var i = 0; i < icon.length; i++) {
                            var tbody = '<td class="icon-td"><a id="icon" onclick="select_icon(this)" href="javascript:void(0)" class="' +
                                icon[i] + '" plain="true" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></td>';
                            if (i == 0) {
                                table += '<tr>' + tbody;
                                continue;
                            }

                            if ((i + 1) % 24 === 0) {
                                table += tbody + '</tr><tr>';
                                continue;
                            }
                            table += tbody;
                        }
                        table += '</tr>';
                        $('#icon-table').append(table);
                    } else {

                    }
                }
            })
        }
        $('#icon-form').form('clear');
        $('#icon-dialog').dialog({
            closed: false,
            modal: true,
            title: "添加菜单信息",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    /*
                    * 获取图标信息
                    * */
                    var iconName = $('.active a').attr('class');
                    $('#add-icon').val(iconName);
                    $('#edit_icon').val(iconName);
                    $('#icon-dialog').dialog('close');
                    $('#wu-datagrid').datagrid('reload');
                }
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#icon-dialog').dialog('close');
                }
            }]
        });
    }

    /**
     * Name 添加记录
     */
    function add() {
        // var validate = $('#-form').form("validate");
        // if(!validate) {
        // $.message.alert("消息提示", "请检查你输入的数据!", "warning");
        // return;
        // }

        var data = $('#add-form').serialize();
        console.log(data);

        $.ajax({
            url: '${pageContext.request.contextPath}/role/add_role',
            data: data,
            type: 'post',
            dataType: 'json',
            success: function (data) {
                if (data.type == 'success') {
                    $.messager.alert('信息提示', data.msg, 'info');
                    $('#add-dialog').dialog('close');
                    $('#icon-dialog').dialog('close');
                    $('#wu-datagrid').treegrid('reload');
                } else {
                    $.messager.alert('信息提示', data.msg, 'info');
                }
            }
        });
    }

    /**
     * Name 修改记录
     */
    function edit() {
        // var validate = $('#menu-form').form("validate");
        // if(!validate) {
        // $.message.alert("消息提示", "请检查你输入的数据!", "warning");
        // return;
        // }

        var data = $('#edit-form').serialize();

        // var edit_form = $('#menu_name').val();
        // console.log(edit_form)
        $.ajax({
            url: '${pageContext.request.contextPath}/role/edit_role',
            data: data,
            type: 'post',
            dataType: 'json',
            success: function (data) {
                if (data.type == 'success') {
                    $.messager.alert('信息提示', '提交成功！', 'info');
                    $('#edit-dialog').dialog('close');
                    $('#icon-dialog').dialog('close');
                    $('#wu-datagrid').treegrid('reload');
                } else {
                    $.messager.alert('信息提示', '提交失败！', 'info');
                }
            }
        });
    }

    /**
     * Name 删除记录
     */
    function remove() {
        $.messager.confirm('信息提示', '确定要删除该记录？', function (result) {
            if (result) {
                var item = $('#wu-datagrid').datagrid('getSelected');
                if (item.id == null) {
                    $.messager.alert('信息提示', '请选择要删除的菜单', 'warning');
                    return;
                }
                //alert(ids);return;
                $.ajax({
                    url: '${pageContext.request.contextPath}/role/delete_role',
                    data: {id: item.id},
                    success: function (data) {
                        if (data.type == 'success') {
                            $.messager.alert('信息提示', '删除成功！', 'info');
                            $('#wu-datagrid').treegrid('reload');
                        } else {
                            $.messager.alert('信息提示', data.msg, 'info');
                        }
                    }
                });
            }
        });
    }

    /**
     * Name 打开添加窗口
     */
    function openAdd() {
        $('#add-form').form('clear');
        $('#add-dialog').dialog({
            closed: false,
            modal: true,
            title: "添加菜单信息",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: add
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#add-dialog').dialog('close');
                }
            }]
        });
    }

    /**
     * Name 打开修改窗口
     */
    function openEdit() {
        $('#edit-form').form('clear');
        var item = $('#wu-datagrid').datagrid('getSelected');
        if (item == null || item.length == 0) {
            $.messager.alert('信息提示', '请选择一条记录！', 'warning');
            return
        }

        $('#edit-dialog').dialog({
            closed: false,
            modal: true,
            title: "修改信息",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: edit
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#edit-dialog').dialog('close');
                }
            }],
            onBeforeOpen: function () {
                $('#edit_id').val(item.id);
                $('#edit_name').val(item.name);
                $('#edit_remark').val(item.remark);
            }
        });
    }

    /**
     * Name 载入数据
     */
    $('#wu-datagrid').treegrid({
        url: '${pageContext.request.contextPath}/role/list',
        rownumbers: true,
        singleSelect: true,
        pageSize: 20,
        pagination: true,
        multiSort: true,
        fitColumns: true,
        fit: true,
        idField: 'id',
        treeField: 'name',
        columns: [[
            {field: 'chk', checkbox: true},
            {field: 'name', title: '用户名', width: 100},
            {field: 'remark', title: '用户备注', width: 100},

            {
                field: 'edit', title: '权限操作', width: 100, formatter: function (value, row, index) {
                    var test = '<a class="auth-edit" onclick="handleAuthEdit('+ row.id +')">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>'
                    return test;
                }
            },
        ]],
        onLoadSuccess: function (data) {
            $('.auth-edit').linkbutton({text: '编辑权限', plain: true, iconCls: 'icon-edit'});
        }
    });
</script>
</body>
</html>